package com.elione.controller.base;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * 
 * @author mhq
 * @version 1.0 (28.08.2015)
 * 
 *
 */
public abstract class AbstractAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -7712900501372966027L;
	
	private Logger logger = LogManager.getLogger( AbstractAction.class );
	
	public static final String _CALLBACK="callback"; 

	private String callback;
	
	public AbstractAction(){
		this.getResponse().setContentType("text/html;charset=utf-8");
		try {
			this.getRequest().setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			logger.warn(" request set encoding error = " + e , e );
		}
	}
	
	public String getCallback() {
		return callback;
	}

	public void setCallback(String callback) {
		this.callback = callback;
	}

	protected HttpSession getSession(){
		return this.getRequest().getSession();
	}
	
	protected HttpSession getSession(boolean arg0){
		return this.getRequest().getSession(arg0);
	}
	
	protected HttpServletRequest getRequest(){
		return ServletActionContext.getRequest();
	}
	
	protected HttpServletResponse getResponse(){
		return ServletActionContext.getResponse();
	}
	
	protected Writer getWriter() throws IOException{
		return getResponse().getWriter();
	}
	
	protected void write(String context){
		if(this.getCallback() ==null)
			outJson(context);
		else
			outJsonp(context);
	}
	
	private void outJson(String context){
		out(context);
	}
	
	private void outJsonp(String context){
		String result=this.getRequest().getParameter(_CALLBACK);
		result+="("+context+")";
		out(result);
	}
	
	private void out(String context){
		try {
			this.getWriter().write(context);
		} catch (Exception e) {
			System.out.println("out exception!");
			e.printStackTrace();
		}
	}

	//public abstract String execute();
	@Override
	public void validate() {
		if(this.getFieldErrors().size()>0){
			throw new RuntimeException("The value of the type mismatch");
		}
		super.validate();
	}
}
